package com.sky.service.impl;

import com.sky.dto.MaterialTemplateDTO;
import com.sky.dto.MaterialTemplatePageQueryDTO;
import com.sky.entity.MaterialTemplate;
import com.sky.exception.BaseException;
import com.sky.mapper.MaterialTemplateMapper;
import com.sky.result.PageResult;
import com.sky.service.MaterialTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 材料模板服务实现类
 */
@Service
@Slf4j
public class MaterialTemplateServiceImpl implements MaterialTemplateService {

    @Autowired
    private MaterialTemplateMapper materialTemplateMapper;

    /**
     * 新增材料模板
     */
    @Override
    @Transactional
    public void add(MaterialTemplateDTO materialTemplateDTO) {
        log.info("新增材料模板：{}", materialTemplateDTO);
        
        // 检查材料名称是否已存在
        MaterialTemplate existTemplate = materialTemplateMapper.selectByMaterialName(materialTemplateDTO.getMaterialName());
        
        if (existTemplate != null) {
            throw new BaseException("材料名称已存在");
        }
        
        MaterialTemplate materialTemplate = new MaterialTemplate();
        BeanUtils.copyProperties(materialTemplateDTO, materialTemplate);
        materialTemplate.setCreateTime(LocalDateTime.now());
        materialTemplate.setUpdateTime(LocalDateTime.now());
        
        log.info("准备插入的材料模板数据：{}", materialTemplate);
        log.info("材料图标URL：{}", materialTemplate.getMaterialIconUrl());
        
        materialTemplateMapper.insert(materialTemplate);
    }

    /**
     * 修改材料模板
     */
    @Override
    @Transactional
    public void update(MaterialTemplateDTO materialTemplateDTO) {
        log.info("修改材料模板：{}", materialTemplateDTO);
        
        // 检查材料模板是否存在
        MaterialTemplate existTemplate = materialTemplateMapper.selectById(materialTemplateDTO.getId());
        if (existTemplate == null) {
            throw new BaseException("材料模板不存在");
        }
        
        // 检查材料名称是否与其他记录重复
        MaterialTemplate duplicateTemplate = materialTemplateMapper.selectByMaterialNameExcludeId(
            materialTemplateDTO.getMaterialName(), materialTemplateDTO.getId());
        
        if (duplicateTemplate != null) {
            throw new BaseException("材料名称已存在");
        }
        
        MaterialTemplate materialTemplate = new MaterialTemplate();
        BeanUtils.copyProperties(materialTemplateDTO, materialTemplate);
        materialTemplate.setUpdateTime(LocalDateTime.now());
        
        log.info("准备更新的材料模板数据：{}", materialTemplate);
        log.info("材料图标URL：{}", materialTemplate.getMaterialIconUrl());
        
        materialTemplateMapper.updateById(materialTemplate);
    }

    /**
     * 删除材料模板
     */
    @Override
    @Transactional
    public void delete(Long id) {
        log.info("删除材料模板：{}", id);
        
        MaterialTemplate materialTemplate = materialTemplateMapper.selectById(id);
        if (materialTemplate == null) {
            throw new BaseException("材料模板不存在");
        }
        
        materialTemplateMapper.deleteById(id);
    }

    /**
     * 批量删除材料模板
     */
    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        log.info("批量删除材料模板：{}", ids);
        
        if (ids == null || ids.isEmpty()) {
            throw new BaseException("删除的ID列表不能为空");
        }
        
        int deletedCount = materialTemplateMapper.batchDeleteByIds(ids);
        log.info("成功删除{}个材料模板", deletedCount);
    }

    /**
     * 分页查询材料模板
     */
    @Override
    public PageResult page(MaterialTemplatePageQueryDTO queryDTO) {
        log.info("分页查询材料模板：{}", queryDTO);
        
        List<MaterialTemplate> records = materialTemplateMapper.selectPageWithCondition(queryDTO);
        Long total = materialTemplateMapper.countWithCondition(queryDTO);
        
        return new PageResult(total, records);
    }

    /**
     * 根据ID查询材料模板
     */
    @Override
    public MaterialTemplate getById(Long id) {
        log.info("根据ID查询材料模板：{}", id);
        
        MaterialTemplate materialTemplate = materialTemplateMapper.selectById(id);
        if (materialTemplate == null) {
            throw new BaseException("材料模板不存在");
        }
        
        return materialTemplate;
    }

    /**
     * 获取所有启用的材料模板
     */
    @Override
    public List<MaterialTemplate> getAllEnabled() {
        log.info("获取所有启用的材料模板");
        return materialTemplateMapper.selectByEnabled(1);
    }

    /**
     * 更新材料模板状态
     */
    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        log.info("更新材料模板状态：id={}, status={}", id, status);
        
        MaterialTemplate materialTemplate = materialTemplateMapper.selectById(id);
        if (materialTemplate == null) {
            throw new BaseException("材料模板不存在");
        }
        
        int updatedCount = materialTemplateMapper.updateStatus(id, status);
        if (updatedCount == 0) {
            throw new BaseException("更新状态失败");
        }
    }

    /**
     * 上传材料图标
     */
    @Override
    public String uploadIcon(MultipartFile file) {
        log.info("上传材料图标：{}", file.getOriginalFilename());
        
        if (file.isEmpty()) {
            throw new BaseException("上传文件不能为空");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new BaseException("只能上传图片文件");
        }
        
        // 检查文件大小（2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            throw new BaseException("图片大小不能超过2MB");
        }
        
        try {
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !originalFilename.contains(".")) {
                throw new BaseException("文件名无效");
            }
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + extension;
            
            // 创建上传目录（使用绝对路径）
            String uploadDir = System.getProperty("user.dir") + File.separator + "uploads" + File.separator + "material-icons" + File.separator;
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                log.info("创建上传目录：{}, 结果：{}", uploadDir, created);
            }
            
            // 保存文件
            String filePath = uploadDir + fileName;
            file.transferTo(new File(filePath));
            log.info("文件保存成功：{}", filePath);
            
            // 返回访问URL（使用线上地址）
            String baseUrl = "https://visa.goldenholiday.com/";
            String relativePath = "uploads/material-icons/" + fileName;
            String fullUrl = baseUrl + relativePath;
            
            log.info("返回文件URL：{}", fullUrl);
            return fullUrl;
            
        } catch (IOException e) {
            log.error("上传文件失败", e);
            throw new BaseException("上传文件失败：" + e.getMessage());
        }
    }
}
